﻿using System;
using System.Collections.Generic;
using System.Text;
using NewsEntity.Models;
using NewsSevicer.Interface;
using System.Linq;
using NewsSevicer.ResultClass;
using Microsoft.AspNetCore.Http;
using Markdig;
using Markdig.SyntaxHighlighting;
using System.Security.Policy;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace NewsSevicer

{
  public  class NewsServer:INews
    {
    
        private NewsContext _context;
        private ITest _test;
        public NewsServer(NewsContext newsContext, ITest test)
        {
            _context = newsContext;
            _test = test;
        }

        public ResultData GetBannerInfo(string url)
        {

            var query = (from d in _context.BannerManager
                         select new BannerManager
                         {
                             ID = d.ID,
                             Image = url + d.Image,
                             Remark = d.Remark,
                             Url = d.Url,
                             AddTime = d.AddTime

                         }).ToList();

            return new ResultData { code = 200, message = "拿到数据了", data = query };

        }

        /// <summary>
        /// 获取所有新闻
        /// </summary>
        /// <param name="Url">添加地址</param>
        /// <returns></returns>
        public Object GetNews(string Url)
        {

            List<AdminNews> list = (from t in _context.News
                           join y in _context.NewsType on t.InfoType equals y.TypeId
                           select new AdminNews
                           {
                               Id = t.Id,
                               TypeInfo = y.TypeName,
                               NewsTitle = t.NewsTitle,
                               NewsContent =  t.NewsContent,
                               PublishDate = t.PublishDate.Value.ToString("yyyy年MM月dd日-H:mm"),
                               Remark = t.Remark,
                               Image = t.Image,
                               NewsStatus = t.NewsStatus,
                               CreateTime = t.CreateTime
                               
                           }).Where(e=>e.NewsStatus==1).OrderByDescending(x=>x.CreateTime).ToList();

            _test.testHi();
            var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()    // 启用高级扩展（如表格、任务列表）
    .UseEmojiAndSmiley()        // 支持 Emoji 表情符号
    .UseMathematics()          // 支持数学公式（LaTeX）
    .Build();                   // 生成最终的 Pipeline
            foreach (var item in list)
            {
              
                //处理图片
                if (!string.IsNullOrEmpty(item.Image))
                {
                    // 使用Split方法将字符串按逗号分割成子字符串数组  
                    string[] parts = item.Image.Split(',');

                    // 将数组中的每个元素添加到List<string>中  
                     item.NewsContent= Markdown.ToHtml(item.NewsContent, pipeline);
                    item.Image = Url + parts[0];
                }
            
            }
           

            return list;
        }

        public ResultData GETNewsComment(int Newsid)
        {
         var query =(from n in _context.NewInfo
                     where n.NewsId == Newsid
                     select new NewInfo {
                     Content=n.Content,
                     NewsId =n.NewsId,
                     CreateTime=n.CreateTime
                     
                     
                     }) .ToList();
            return new ResultData { code = 200, message = "拿到数据了", data = query };
        }
        /// <summary>
        /// 最新评论的新闻
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ResultData GetPLNews(string url)
        {
            var query = (from t in _context.News
                         join y in _context.NewInfo on t.Id equals y.NewsId
                         orderby y.CreateTime descending
                         select new NewsPL {
                         Id = t.Id,
                          NewsContent=t.NewsContent,
                          PublishDate=t.PublishDate.Value.ToString("yyyy年MM月dd日-H:mm"),
                             NewsTitle =t.NewsTitle,
                          Image=  t.Image,
                          NewsStatus=t.NewsStatus,
                          InfoType = t.InfoType,
                          Remark=t.Remark,
                         
                         } ).ToList().Take(10);

            foreach (var item in query)
            {

                //处理图片
                if (!string.IsNullOrEmpty(item.Image))
                {
                    // 使用Split方法将字符串按逗号分割成子字符串数组  
                    string[] parts = item.Image.Split(',');
                    var pipeline = new MarkdownPipelineBuilder()
                        .UseAdvancedExtensions()    // 启用高级扩展（如表格、任务列表）
                        .UseEmojiAndSmiley()        // 支持 Emoji 表情符号
                        .UseMathematics()          // 支持数学公式（LaTeX）
                        .Build();                   // 生成最终的 Pipeline
                    // 将数组中的每个元素添加到List<string>中  
                    item.NewsContent = Markdown.ToHtml(item.NewsContent,pipeline);
                    item.Image = url + parts[0];
                }

            }


            //Take(10)拿去10条数据
            return new ResultData { code = 200, message = "评论新闻拿到数据了",data = query};
         
        }

        /// <summary>
        /// 返回新闻类型
        /// </summary>
        /// <returns></returns>
        public List<NewsType> GetNewsType()
        {
            List<NewsType> list = _context.NewsType.ToList();
            return list;
        }

        /// <summary>
        /// 获取单一的新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public News GetSingleNews(int id)
        {

            //var list= _context.News.Find(id);
            // var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().UseSyntaxHighlighting().Build();
            // list.NewsContent = Markdown.ToHtml(list.NewsContent, pipeline);
            // //list.NewsContent =  Markdown.ToHtml(list.NewsContent);
            // list.PublishDate.Value.ToString("yyyy年MM月dd日-H:mm");

            // if (list!=null)
            // {
            //     return list;

            // }
            // return null;


            var news = _context.News.Find(id);

            if (news != null)
            {
                var pipeline = new MarkdownPipelineBuilder()
                             .UseAdvancedExtensions()    // 启用高级扩展（如表格、任务列表）
                             .UseEmojiAndSmiley()        // 支持 Emoji 表情符号
                             .UseMathematics()          // 支持数学公式（LaTeX）
                             .Build();                   // 生成最终的 Pipeline                 // 生成最终的 Pipeline
                news.NewsContent = Markdown.ToHtml(news.NewsContent, pipeline);
                news.PublishDate.Value.ToString("yyyy年MM月dd日-H:mm");
                return news;
            }

            return null;



        }

        /// <summary>
        /// 获取新闻类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<News> GetTypeNews(int id)
        {
            List<News> newsList = new List<News>();

            try
            {
                //NewsStatus==1 文字状态为发布状态
                newsList = _context.News
                    .Where(m => m.InfoType == id && m.NewsStatus == 1)
                    .ToList();
                var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()    // 启用高级扩展（如表格、任务列表）
    .UseEmojiAndSmiley()        // 支持 Emoji 表情符号
    .UseMathematics()          // 支持数学公式（LaTeX）
    .Build();                   // 生成最终的 Pipeline
                foreach (var item in newsList)
                {
                    try
                    {
                        // 将内容转换为HTML
                        item.NewsContent = Markdown.ToHtml(item.NewsContent, pipeline);

                        // 处理图片
                        if (!string.IsNullOrEmpty(item.Image))
                        {
                            // 使用Split方法将字符串按逗号分割成子字符串数组  
                            string[] parts = item.Image.Split(',');

                            // 使用第一个图片作为主图片
                            item.Image = parts[0];
                        }
                    }
                    catch (Exception ex)
                    {
                        // 处理单个新闻项目的异常，比如记录日志
                        Console.WriteLine($"Error processing news item ID {item.Id}: {ex.Message}");
                        // 继续处理其他新闻项目
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理整个方法的异常，比如记录日志或返回一个友好的错误信息
                Console.WriteLine($"Error retrieving news items: {ex.Message}");
                return newsList;
            }
            return newsList;
        }

        /// <summary>
        /// 新闻评论
        /// </summary>
        /// <param name="newInfo"></param>
        /// <returns></returns>
        public bool NewsComment(NewInfo newInfo)
        {

            try
            {
                _context.NewInfo.Add(newInfo);
                _context.SaveChanges();
                return true;
               
            }
            catch (Exception)
            {

                return false;
            }
        }

        /// <summary>
        /// 获取单个新闻name
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetNewsType(int id)
        {
            try
            {
                var list = _context.NewsType.Find(id);

                return list.TypeName.Trim();
            }
            catch (Exception)
            {

                return "出错了";
            }
        }
    }
}
